package com.goods.business.service.imp;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.goods.business.mapper.*;
import com.goods.business.service.OutStockService;
import com.goods.common.model.business.*;
import com.goods.common.vo.business.ConsumerVO;
import com.goods.common.vo.business.OutStockDetailVO;
import com.goods.common.vo.business.OutStockItemVO;
import com.goods.common.vo.business.OutStockVO;
import com.goods.common.vo.system.PageVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
public class OutStockServiceImpl implements OutStockService {

    @Autowired
    private OutStockMapper outStockMapper;

    @Autowired
    private ConsumerMapper consumerMapper;

    @Autowired
    private OutStockInfoMapper outStockInfoMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ProductStockMapper productStockMapper;

    //出库单（发放记录）数据分页列表展示
    @Override
    public PageVO<OutStockVO> findOutStockList(Integer pageNum, Integer pageSize, Integer status, String outNum, Integer type) {
        PageHelper.startPage(pageNum,pageSize);
        Example example = new Example(OutStock.class);
        Example.Criteria criteria = example.createCriteria();
        if (null != status){
            criteria.andEqualTo("status",status);
        }
        if (!StringUtils.isEmpty(outNum)){
            criteria.andLike("outNum","%" + outNum + "%");
        }
        if (null != type){
            criteria.andEqualTo("type",type);
        }
        List<OutStock> outStockList = outStockMapper.selectByExample(example);
        List<OutStockVO> outStockVOList = outStockList.stream().map(outStock -> {
            OutStockVO outStockVO = new OutStockVO();
            BeanUtils.copyProperties(outStock, outStockVO);
            Long consumerId = outStock.getConsumerId();
            Consumer consumer = consumerMapper.selectByPrimaryKey(consumerId);
            if (consumer != null){
                outStockVO.setName(consumer.getName());
                outStockVO.setAddress(consumer.getAddress());
                outStockVO.setPhone(consumer.getPhone());
                outStockVO.setContact(consumer.getContact());
                outStockVO.setSort(consumer.getSort());
            }
            return outStockVO;
        }).collect(Collectors.toList());
        PageInfo<OutStock> pageInfo = new PageInfo<>(outStockList);
        return new PageVO<>(pageInfo.getTotal(),outStockVOList);
    }

    //物资明细列表
    @Override
    public OutStockDetailVO detailOutStock(Long id, Integer pageNum, Integer pageSize) {
        OutStockDetailVO outStockDetailVO = new OutStockDetailVO();
        OutStock outStock = outStockMapper.selectByPrimaryKey(id);
        outStockDetailVO.setOutNum(outStock.getOutNum());
        outStockDetailVO.setStatus(outStock.getStatus());
        outStockDetailVO.setType(outStock.getType());
        outStockDetailVO.setOperator(outStock.getOperator());
        Consumer consumer = consumerMapper.selectByPrimaryKey(outStock.getConsumerId());
        ConsumerVO consumerVO = new ConsumerVO();
        if (null != consumer){
            BeanUtils.copyProperties(consumer,consumerVO);
        }
        outStockDetailVO.setConsumerVO(consumerVO);
        //List<OutStockItemVO> itemVOS = new ArrayList<>();
        OutStockInfo outStockInfo = new OutStockInfo();
        outStockInfo.setOutNum(outStock.getOutNum());
        PageHelper.startPage(pageNum,pageSize);
        List<OutStockInfo> outStockInfoList = outStockInfoMapper.select(outStockInfo);
        List<OutStockItemVO> outStockItemVOList = outStockInfoList.stream().map(outStockInfo1 -> {
            OutStockItemVO outStockItemVO = new OutStockItemVO();
            Product productTerm = new Product();
            productTerm.setPNum(outStockInfo1.getPNum());
            Product product = productMapper.selectOne(productTerm);
            outStockItemVO.setId(product.getId());
            outStockItemVO.setPNum(product.getPNum());
            outStockItemVO.setName(product.getName());
            outStockItemVO.setModel(product.getModel());
            outStockItemVO.setUnit(product.getUnit());
            outStockItemVO.setImageUrl(product.getImageUrl());
            outStockItemVO.setCount(outStockInfo1.getProductNumber());
            return outStockItemVO;
        }).collect(Collectors.toList());
        PageInfo<OutStockInfo> pageInfo = new PageInfo(outStockInfoList);
        outStockDetailVO.setTotal(pageInfo.getTotal());
        outStockDetailVO.setItemVOS(outStockItemVOList);
        return outStockDetailVO;
    }

    //将出库单移入回收站
    @Override
    public void removeOutStock(Long id) {
        OutStock outStock = new OutStock();
        outStock.setId(id);
        outStock.setStatus(1);
        outStockMapper.updateByPrimaryKeySelective(outStock);
    }

    //将回收站的出库单还原
    @Override
    public void backOutStock(Long id) {
        OutStock outStock = new OutStock();
        outStock.setId(id);
        outStock.setStatus(0);
        outStockMapper.updateByPrimaryKeySelective(outStock);
    }

    //删除出库单
    @Override
    public void deleteOutStock(Long id) {
        outStockMapper.deleteByPrimaryKey(id);
    }

    //添加出库单（发放物资）
    @Override
    public void addOutStock(Map<String, Object> map) {
        //新增去向保存DB
        Calendar calendar = Calendar.getInstance();
        OutStock outStock = new OutStock();
        if (!map.containsKey("consumerId")){
            Consumer consumer = new Consumer();
            consumer.setName(map.get("name").toString());
            consumer.setAddress(map.get("address").toString());
            consumer.setCreateTime(calendar.getTime());
            consumer.setModifiedTime(calendar.getTime());
            consumer.setPhone(map.get("phone").toString());
            consumer.setSort(Integer.parseInt(map.get("sort").toString()));
            consumer.setContact(map.get("contact").toString());
            consumerMapper.insertSelective(consumer);
            outStock.setConsumerId(consumer.getId());
        } else {
            outStock.setConsumerId(Long.parseLong(map.get("consumerId").toString()));
        }
        //保存出库单和出库单明细
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        outStock.setOutNum(uuid);
        outStock.setType(Integer.parseInt(map.get("type").toString()));
        outStock.setOperator("admin");
        outStock.setCreateTime(calendar.getTime());
        Integer productNumbers = 0;
        List<Map> listMap = (List<Map>) map.get("products");
        for (Map productMap : listMap) {
            Long productId = Long.parseLong(productMap.get("productId").toString());
            Integer productNumber = Integer.parseInt(productMap.get("productNumber").toString());
            Product product = productMapper.selectByPrimaryKey(productId);
            OutStockInfo outStockInfo = new OutStockInfo();
            outStockInfo.setOutNum(uuid);
            outStockInfo.setPNum(product.getPNum());
            outStockInfo.setProductNumber(productNumber);
            outStockInfo.setCreateTime(calendar.getTime());
            outStockInfo.setModifiedTime(calendar.getTime());
            productNumbers = productNumbers + productNumber;
            outStockInfoMapper.insertSelective(outStockInfo);
        }
        outStock.setProductNumber(productNumbers);
        outStock.setRemark(map.get("remark").toString());
        outStock.setStatus(2);
        outStock.setPriority(Integer.parseInt(map.get("priority").toString()));
        outStockMapper.insertSelective(outStock);
    }

    //更改审核状态
    @Override
    public void publishOutStock(Long id) {
        OutStock outStock = new OutStock();
        outStock.setId(id);
        outStock.setStatus(0);
        outStockMapper.updateByPrimaryKeySelective(outStock);
    }

    //更新库存数量
    @Override
    public void lessProductStock(Long id) {
        OutStock outStock = outStockMapper.selectByPrimaryKey(id);
        OutStockInfo outStockInfoTerm = new OutStockInfo();
        outStockInfoTerm.setOutNum(outStock.getOutNum());
        List<OutStockInfo> outStockInfoList = outStockInfoMapper.select(outStockInfoTerm);
        for (OutStockInfo outStockInfo : outStockInfoList) {
            ProductStock productStockTerm = new ProductStock();
            productStockTerm.setPNum(outStockInfo.getPNum());
            ProductStock productStock = productStockMapper.selectOne(productStockTerm);
            if (productStock.getStock() >= outStockInfo.getProductNumber()){
                productStock.setStock(productStock.getStock() - outStockInfo.getProductNumber());
            }
            productStockMapper.updateByPrimaryKeySelective(productStock);
        }
    }
}
